package model.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import model.bean.Chat;
import model.common.Common;

public class BlogDao {
	public boolean InsertChat(String userName,String comment){
		String sql = "INSERT INTO tblComments(userName,time,comment) VALUES(?,GETDATE(),N'"+comment+"')";
		try {
			Common.connect();
			PreparedStatement pst = Common.conn.prepareStatement(sql);
			pst.setString(1, userName);
			if (pst.executeUpdate()!=0) {
				return true;

			}
		} catch (SQLException e) {
			System.err.println("Da co loi xay ra. Them binh luan khong thanh cong!!!");
			e.printStackTrace();
		} finally {
			Common.disconnect();
		}
		return false;
	}
	
	public ArrayList<Chat> getChat() {
		ArrayList<Chat> listChat = new ArrayList<Chat>();
		Chat chat = null;
//		String sql = "SELECT userName,time,comment FROM tblComments inner join tblAccount on tblComments.userName = tblAccount.userName ORDER BY time DESC";
		String sql = "SELECT chatId,userName,time,comment FROM tblComments  ORDER BY chatId DESC";
		try {
			Common.connect();
			PreparedStatement pst = Common.conn.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				chat = new Chat();
				
				chat.setChatId(rs.getInt("chatId"));
				chat.setUserName(rs.getString("userName"));
				chat.setTime(rs.getString("time"));
				chat.setComment(rs.getString("comment"));
				
				listChat.add(chat);
			}
		} catch (SQLException e) {
			System.err.println("Da co loi xay ra. Không lấy được dữ liệu !!!");
			e.printStackTrace();
		} finally {
			Common.disconnect();
		}
		return listChat;
	}
	
	/**
	 * Delete comment of user
	 * @param userName
	 * @param comment
	 * @return
	 */
	public boolean DeleteChat(int chatId){
		String sql = "delete from tblComments where chatId=?";
		try {
			Common.connect();
			PreparedStatement pst = Common.conn.prepareStatement(sql);
			pst.setInt(1, chatId);
			if (pst.executeUpdate()!=0) {
				return true;

			}
		} catch (SQLException e) {
			System.err.println("Da co loi xay ra. Khong xoa duoc binh luan !!!");
			e.printStackTrace();
		} finally {
			Common.disconnect();
		}
		return false;
	}
	
	
	public static void main(String[] args) {
		BlogDao blogDao = new BlogDao();
		blogDao.getChat();
	}
	
	
}
